package com.unitd.base.module.consumer.comm.interceptor;

import com.unitd.base.module.comm.exception.ApiRRException;
import com.unitd.base.module.consumer.comm.annotation.IgnoreAuth;
import com.unitd.base.module.master.service.TokenService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 自定义拦截器,用于拦截用户请求对用户权限(Token)验证
 *
 * @author Hudan
 * @version 1.0
 * @filename AuthorizationInterceptor.java
 * @copyright www.unitd.com
 * @date 2020-07-09
 */
@Component
public class AuthorizationInterceptor extends HandlerInterceptorAdapter {

    /** 登录用户的KEY */
    public static final String LOGIN_USER_KEY = "LOGIN_USER_KEY";
    /** 请求头中的token的key */
    public static final String LOGIN_TOKEN_KEY = "X-Nideshop-Token";
    @Autowired
    private TokenService tokenService;

    /**
     * 拦截器前置处理
     *
     * @param request  当前请求
     * @param response 请求反馈
     * @param handler  处理器
     * @return 拦截结果
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {

        // 支持跨域请求
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.setHeader("Access-Control-Allow-Headers", "x-requested-with,X-Nideshop-Token,X-URL-PATH");
        response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));

        IgnoreAuth annotation;
        if (handler instanceof HandlerMethod) {
            annotation = ((HandlerMethod) handler).getMethodAnnotation(IgnoreAuth.class);
        } else {
            return true;
        }

        // 如果有@IgnoreAuth注解，则不验证token
        if (annotation != null) {
            return true;
        }

        // 从header中获取token
        String token = request.getHeader(LOGIN_TOKEN_KEY);
        // 如果header中不存在token，则从参数中获取token
        if (StringUtils.isBlank(token)) {
            token = request.getParameter(LOGIN_TOKEN_KEY);
        }

        // token为空
        if (StringUtils.isBlank(token)) {
            throw new ApiRRException("请先登录", 401);
        }

        // 查询token信息
        Long userId = tokenService.getUserIdByToken(token);
        if (userId == null) {
            throw new ApiRRException("token失效，请重新登录", 401);
        }

        // 设置userId到request里，后续根据userId，获取用户信息
        request.setAttribute(LOGIN_USER_KEY, userId);
        return true;
    }
}